package cn.hfatec.shms.web.xc.xcMplan.service;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;


import cn.hfatec.shms.advice.annotation.OracleDataSource;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.web.xh.xhSmjdb.model.XhSmjdb;
import cn.hfatec.shms.web.xh.xhSmjdb.model.XhSmjdbParams;
import cn.hfatec.shms.web.xh.xhZjmy.model.XhZjmy;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hfatec.base.BaseDao;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.shms.web.xc.xcMplan.model.XcMplan;
import cn.hfatec.shms.web.xc.xcMplan.dao.XcMplanDao;
import cn.hfatec.shms.web.xc.xcMplan.model.XcMplanParams;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * @author hfatec
 * @version 1.0
 *
 * the JAVA code is generate by middlegen
 *
 */
@Service("XcMplanService")
public class XcMplanService {

    public static final String BEAN_ID = "XcMplanService";

    //注入Dao层
    @Resource(name = "XcMplanDao")
    private XcMplanDao xcMplanDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    @Transactional
    @OracleDataSource
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     *
     * 查询数据
     *
     * @param xcMplanParams
     * @param page
     *
     */
    @Transactional
    @OracleDataSource
    public Table queryXcMplanTable(XcMplanParams xcMplanParams, Page page){

        HashMap<String, Object> params = new HashMap<String, Object>();
        if (null == page) page = new Page();
        //起始点
        int offset = page.getPageSize() * (page.getCurrentPage() - 1) + 1;
        //查询的记录数
        int limit = offset + page.getPageSize() - 1;
        xcMplanParams.setStartPage(offset);
        xcMplanParams.setEndPage(limit);
        XcMplan xcMplan = getXcMplan(xcMplanParams);
        if (xcMplan != null) {
            page.setTotalPage(xcMplan.getTotal() / page.getPageSize() + 1);
            page.setTotalSize(xcMplan.getTotal());
        } else {
            page.setTotalPage(0);
            page.setTotalSize(0);
        }
        params.put("params", xcMplanParams);
        return baseDao.queryTableByPageOracle("queryXcMplan", params, page);
    }

    /**
     *
     * 根据ID获取数据
     * @param xcMplanParams
     *
     */
    @Transactional
    @OracleDataSource
    public XcMplan getXcMplan(XcMplanParams xcMplanParams) {

        return xcMplanDao.getXcMplanById(xcMplanParams);
    }

    /**
     *
     * 根据ID获取数据
     * @param xcMplanParams
     *
     */
    @Transactional
    @OracleDataSource
    public List getXcMplanList(XcMplanParams xcMplanParams) {

        return xcMplanDao.getXcMplanList(xcMplanParams);
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    @OracleDataSource
    public String exportExcel(XcMplanParams xcMplanParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList =xcMplanDao.queryXcMplanExcel(xcMplanParams);
            List nameList = new ArrayList();
            nameList.add("年");
            nameList.add("管理医生");
            nameList.add("一月");
            nameList.add("二月");
            nameList.add("三月");
            nameList.add("四月");
            nameList.add("五月");
            nameList.add("六月");
            nameList.add("七月");
            nameList.add("八月");
            nameList.add("九月");
            nameList.add("十月");
            nameList.add("十一月");
            nameList.add("十二月");
            nameList.add("干预提示");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> vipTypeList = CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE);
        List<CodeInfo> overdueTypeList = CodeInfoCache.getCodeInfo(CodeType.OVERDUE_TYPE);

        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("回访月计划");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        XcMplan xcMplan = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            xcMplan = (XcMplan) fieldData.get(i);
            // 第四步，创建单元格，并设置值

            if (xcMplan.getNian() == null) {
                row.createCell((short) 0).setCellValue("");
            } else {
                row.createCell((short) 0).setCellValue(xcMplan.getNian());
            }
            if (xcMplan.getRealName() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(xcMplan.getRealName());
            }
            if (xcMplan.getJan() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {
                row.createCell((short) 2).setCellValue(xcMplan.getJan());
            }
            if (xcMplan.getFeb() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                row.createCell((short) 3).setCellValue(xcMplan.getFeb());
            }
            if (xcMplan.getMar() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                row.createCell((short) 4).setCellValue(xcMplan.getMar());
            }
            if (xcMplan.getApr() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                row.createCell((short) 5).setCellValue(xcMplan.getApr());
            }
            if (xcMplan.getMay() == null) {
                row.createCell((short) 6).setCellValue("");
            } else {
                row.createCell((short) 6).setCellValue(xcMplan.getMay());
            }
            if (xcMplan.getJun() == null) {
                row.createCell((short) 7).setCellValue("");
            } else {
                row.createCell((short) 7).setCellValue(xcMplan.getJun());
            }
            if (xcMplan.getJul() == null) {
                row.createCell((short) 8).setCellValue("");
            } else {
                row.createCell((short) 8).setCellValue(xcMplan.getJul());
            }
            if (xcMplan.getAug() == null) {
                row.createCell((short) 9).setCellValue("");
            } else {
                row.createCell((short) 9).setCellValue(xcMplan.getAug());
            }
            if (xcMplan.getSep() == null) {
                row.createCell((short) 10).setCellValue("");
            } else {
                row.createCell((short) 10).setCellValue(xcMplan.getSep());
            }
            if (xcMplan.getOct() == null) {
                row.createCell((short) 11).setCellValue("");
            } else {
                row.createCell((short) 11).setCellValue(xcMplan.getOct());
            }
            if (xcMplan.getNov() == null) {
                row.createCell((short) 12).setCellValue("");
            } else {
                row.createCell((short) 12).setCellValue(xcMplan.getNov());
            }

            if (xcMplan.getDece() == null) {
                row.createCell((short) 13).setCellValue("");
            } else {
                row.createCell((short) 13).setCellValue(xcMplan.getDece());
            }
            if (xcMplan.getPlanRemind() == null) {
                row.createCell((short) 14).setCellValue("");
            } else {
                row.createCell((short) 14).setCellValue(xcMplan.getPlanRemind());
            }

        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }


        return wb;
    }


    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }

}